package com.hxzy.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author nick
 * WebServlet 注解中包含的常用属性
 * value属性：url映射，根据url映射，访问web容器中的ServletLifeCycle的实例
 * loadOnStartup：默认为-1，第一次访问url映射时，才会将这个url映射对应的实例加载到web容器
 *                手动设置loadOnStartup为自定义数值后，服务器启动时就会实例化servlet实例并加载到web容器
 * initParams:在启动servlet时，为servlet配置初始化参数
 *          注解的参数类型为@WebInitParam
 *                  name属性：要设置的参数的名称
 *                  value属性：要设置的参数的值
 */
@WebServlet(value = "/lifeCycle",loadOnStartup = 1,initParams = {@WebInitParam(name = "encode",value="utf-8")})
public class ServletLifeCycle extends HttpServlet {

    //设置编码方式
    private String encode = "GBK";
    @Override
    public void init() throws ServletException {
        super.init();
        System.out.println("==========ServletLifeCycle.class  init() ============");
    }

    @Override
    public void init(ServletConfig config) throws ServletException {

        System.out.println("==========ServletLifeCycle.class  init(ServletConfig config) ============");
        //ServletConfig的对象实际上就是jsp的内置对象config
        //用于获取配置servlet初始化参数的对象
        String encode = config.getInitParameter("encode");
        System.out.println("=========读取到初始化参数encode：" + encode);
        this.encode = encode;
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("=========ServletLifeCycle.class service() ===========");

        //响应客户端之前设置编码方式
        resp.setCharacterEncoding(this.encode);

        //设置响应的MIME
        resp.setContentType("text/html;charset=utf-8");//教浏览器做事。告诉浏览器，本次响应的内容用html解析
        PrintWriter writer = resp.getWriter();
        //服务端响应客户端的内容
        writer.write("我是servlet，我接收到了你的请求，你放心的去吧");

        //输出流打开后需要刷新缓存
        writer.flush();
        //关闭输出流
        writer.close();
    }

    @Override
    public void destroy() {
        System.out.println("=========ServletLifeCycle.class destroy() =========");
    }

}
